<?php
namespace php\geo\googlemaps;

use php\core\Object;
use php\geo\Position;
use php\mvc\App;
    
class StaticImage extends Object {

    protected static $PROTOCOL = "http";
    protected static $MAPS_HOST = "maps.google.com";
    protected static $MAPS_PATH = "maps/api/staticmap";

    private $zoom;
    private $size;
    private $mapType;
    private $center;
    private $markers;

    public function __construct(ImageSize $size) {
        $this->size = $size;
        $this->mapType = MapType::ROADMAP();
        $this->zoom = 15;
        $this->markers = array();
    }

    public function setCenter($positionOrAddress) {
        $this->center = $positionOrAddress;
    }

    public function getCenter() {
        return $this->center;
    }

    public function addMarker( MapMarker $marker ) {
        $this->markers[] = $marker;
    }

    /*
     * Returns de url of google googlemaps image
     *
     * e.g. http://maps.google.com/maps/api/staticmap?sensor=false&zoom=15&size=486x130&maptype=roadmap&markers=color:blue|label:|40.4608909,-3.8753010
     */
    public function getURL() {
        $params = $this->getParams();
        $paramsStr = "";
        $app = "";
        foreach ($params as $param) {
            list($name, $value) = $param;
            $paramsStr .= $app . urlencode($name) . "=" . urlencode(App::encode($value));
            $app = "&";
        }

        $url = sprintf("%s://%s/%s?%s"
            , self::$PROTOCOL, self::$MAPS_HOST
            , self::$MAPS_PATH, $paramsStr );

        return $url;
    }

    public function setMapType(MapType $mapType) {
        $this->mapType = $mapType;
    }

    public function getMapType() {
        return $this->mapType;
    }

    public function setSize(ImageSize $size) {
        $this->size = $size;
    }

    public function getSize() {
        return $this->size;
    }

    public function setZoom($zoom) {
        $this->zoom = $zoom;
    }

    public function getZoom() {
        return $this->zoom;
    }

    private function getParams() {
        $params = array();
        $params[] = array("sensor", "false");
        $params[] = array("zoom", $this->getZoom());
        $params[] = array("size", $this->getSize()->asString());
        $params[] = array("maptype", $this->getMapType()->getType() );
        $hasMarkers = false;
        foreach( $this->markers as $marker) {
            $params[] = array("markers", $marker->asString() );
            $hasMarkers = true;
        }

        if ($this->getCenter()!=null) {
            $params[] = array("center", $this->getCenter());
        }
        elseif (!$hasMarkers) {
            throw new Exception("With no markers you must specify center");
        }
        
        return $params;
    }

}
